package com.example.mybatis.controller;

import com.alibaba.fastjson.JSON;
import com.example.mybatis.entity.User;
import com.example.mybatis.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author ：xiongwei
 * @date ：Created in 2020/11/8 21:23
 */
@RestController
@RequestMapping("user")
@Api(value = "用户操作", tags = "用户操作相关API")
public class UserController {

    @Autowired
    UserService userService;

    @PostMapping("/saveUser")
    @ApiOperation(value = "新增用户", notes = "用户")
    public String insertUser(@RequestBody User user) {
        String result = "";
        int saveResult = 0;
        try {
            saveResult = userService.insertUser(user);
            result = saveResult + "";
        } catch (Exception e) {
            result = e.getMessage();
        }
        return result;
    }

    @PostMapping("/updateUser")
    @ApiOperation(value = "修改用户", notes = "用户")
    public String updateUser(@RequestBody User user) {
        String result = "";
        int updateResult = 0;
        try {
            updateResult = userService.updateUser(user);
            result = updateResult + "";
        } catch (Exception e) {
            result = e.getMessage();
        }
        return result;
    }

    @PostMapping("/updateUserBySql")
    @ApiOperation(value = "修改用户", notes = "用户")
    public String updateUserBySql(@RequestBody User user) {
        String result = "";
        int updateResult = 0;
        try {
            updateResult = userService.updateUserBySql(user);
            result = updateResult + "";
        } catch (Exception e) {
            result = e.getMessage();
        }
        return result;
    }

    @DeleteMapping("/deleteUser/{userId}")
    @ApiOperation(value = "删除用户", notes = "用户")
    public String deleteUser(String userId) {
        String result = "";
        try {
            Long id = Long.parseLong(userId);
            result = userService.deleteUser(id) + "";
        } catch (Exception e) {
            result = e.getMessage();
        }
        return result;
    }

    @GetMapping("/getUser")
    @ApiOperation(value = "获取用户", notes = "用户")
    public String getUser() {
        String result = "";
        try {
            List<User> userList = userService.getUsers();
            result = JSON.toJSONString(userList);
        } catch (Exception e) {
            result = e.getMessage();
        }
        return result;
    }

}
